package com.crm.log.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import com.crm.custinfo.service.impl.UserInfoComm;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.crm.log.mapper.UserBusinessLogMapper;
import com.crm.log.domain.UserBusinessLog;
import com.crm.log.service.IUserBusinessLogService;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 日志报表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-12
 */
@Service
public class UserBusinessLogServiceImpl implements IUserBusinessLogService 
{
    @Autowired
    private UserBusinessLogMapper userBusinessLogMapper;

    @Autowired
    private ISysDeptService isysDeptService;
    @Autowired
    private UserInfoComm userInfoComm;
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 查询日志报表
     * 
     * @param id 日志报表主键
     * @return 日志报表
     */
    @Override
    public UserBusinessLog selectUserBusinessLogById(Long id)
    {
        return userBusinessLogMapper.selectUserBusinessLogById(id);
    }

    /**
     * 查询日志报表列表
     * 
     * @param userBusinessLog 日志报表
     * @return 日志报表
     */
    @Override
    public List<UserBusinessLog> selectUserBusinessLogList(UserBusinessLog userBusinessLog)
    {
        return userBusinessLogMapper.selectUserBusinessLogList(userBusinessLog);
    }

    /**
     * 新增日志报表
     * 
     * @param userBusinessLog 日志报表
     * @return 结果
     */
    @Override
    public int insertUserBusinessLog(UserBusinessLog userBusinessLog)
    {
        userBusinessLog.setCreateTime(DateUtils.getNowDate());
        return userBusinessLogMapper.insertUserBusinessLog(userBusinessLog);
    }

    /**
     * 修改日志报表
     * 
     * @param userBusinessLog 日志报表
     * @return 结果
     */
    @Override
    public int updateUserBusinessLog(UserBusinessLog userBusinessLog)
    {
        userBusinessLog.setUpdateTime(DateUtils.getNowDate());
        return userBusinessLogMapper.updateUserBusinessLog(userBusinessLog);
    }

    /**
     * 批量删除日志报表
     * 
     * @param ids 需要删除的日志报表主键
     * @return 结果
     */
    @Override
    public int deleteUserBusinessLogByIds(Long[] ids)
    {
        return userBusinessLogMapper.deleteUserBusinessLogByIds(ids);
    }

    /**
     * 删除日志报表信息
     * 
     * @param id 日志报表主键
     * @return 结果
     */
    @Override
    public int deleteUserBusinessLogById(Long id)
    {
        return userBusinessLogMapper.deleteUserBusinessLogById(id);
    }

    /**
     * @param type            0-查询 1-导出
     * @param userBusinessLog
     * @return
     */
    @Override
    public Map<String, Object> getUserBusinessLogs(int type, UserBusinessLog userBusinessLog) {
        SysUser user = getLoginUser().getUser();
        Map<String,Object> resMap=new HashMap<String,Object>();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = userBusinessLog.getOrgId() == null || userBusinessLog.getOrgId() == -1L ? user.getDeptId() : userBusinessLog.getOrgId();

        List<SysDept> sysDeptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Long[] orgIds = new Long[sysDeptList.size()];
        for (int i = 0; i < sysDeptList.size(); i++) {
            SysDept sysDept = sysDeptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }


        Map<String,Object> params =userBusinessLog.getParams();

        params.put("orgIds", orgIds);
        params.put("orgId", null);

        // 业务员只能看到本人的日志
        SysDept org = getLoginUser().getUser().getDept();

        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        if (Objects.equals(org.getLevel(),TypeConstant.ORG_LEVEL_4) ) {
            if (roleMap.get("depart_leader").equals("0")) { // 业务员
                userBusinessLog.setEmpId(user.getUserId());
            }
        }
        String logDateStart=MapUtils.getString(params,"beginlogDate");
        String curdate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date());
        if(MapUtils.getString(params,"beginlogDate","").equals("")) {
            params.put("beginlogDate",curdate);
            params.put("endlogDate",curdate);
        }
        userBusinessLog.setParams(params);
       List<UserBusinessLog> list= this.selectUserBusinessLogList(userBusinessLog);



        for (UserBusinessLog log : list) {
            log.setTodayDistributeTotal(0l);
            if (log.getTodayDistributeCount()!=null && log.getTodayDistributeCount() > 0) {
                log.setTodayDistributeTotal(Long.valueOf(log.getTodayDistributeDetail().split(",").length));
            }
            if (log.getTodayAddmustCount()!=null && log.getTodayAddmustCount() > 0) {
                log.setTodayAddmustTotal(Long.valueOf(log.getTodayAddmustDetail().split(",").length));
            }
        }

        if (type == 0) {  // 查询
            // 不需要提交日志的角色代码
            String noLogRoles = baseSysConfigService.getItemValueByItemKey(ConfigConstant.ROLE_CODES_LOG_NONEED, "boss,branchGM,areaLeader,administration,finance,admin");
            // 当日提交日志情况统计
            if ("".equals(logDateStart) && (roleMap.get("depart_leader").equals("1") || roleMap.get("company_leader").equals("1")
                    || roleMap.get("sub_leader").equals("1") || roleMap.get("area_leader").equals("1"))) {
                // 当前部门下当日应提交日志数
                int needCount = 0;
                // 当前部门下当日已提交日志数
                int logCount = 0;
                // 哪些用户未提交日志
                String nologStr = "";
                Map<String,Object> inParams = new HashMap<String,Object>();
                SysUser user_in = new SysUser();
                inParams.put("logDate",curdate);
                inParams.put("noLog","");
                user_in.setParams(inParams);
                // 需提交日志的用户
                List<SysUser> needLogUsers = filterAllNeedLogUsers(userService.findAllNeedLogUsers(user_in), noLogRoles);
                needCount = needLogUsers.size();
                logCount = list.size();
                if (needCount > logCount) {
                    inParams.put("noLog",1);
                    user_in.setParams(inParams);

                    List<SysUser> nologUsers = filterAllNeedLogUsers(userService.findAllNeedLogUsers(user_in), noLogRoles);
                    for (SysUser nologUser : nologUsers) {
                        nologStr += nologUser.getNickName() + ",";
                    }
                    if (StringUtils.isNotBlank(nologStr)) {
                        nologStr = nologStr.substring(0, nologStr.length() - 1);
                    }
                }
                resMap.put("needCount", needCount);
                resMap.put("logCount", logCount);
                resMap.put("nologStr", nologStr);
            }
        }

        resMap.put("list", list);
        resMap.put("userBusinessLog", userBusinessLog);
        resMap.put("roleMap", roleMap);

        return resMap;
    }
    /**
     * 个人汇总排行
     * 20200803: 新增  --
     * @return
     */
    @Override
    public Map<String,Object> getUserBusinessSumLogs(int type, UserBusinessLog userBusinessLog) throws Exception {
        SysUser user = getLoginUser().getUser();
        Map<String,Object> resMap=new HashMap<String,Object>();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = userBusinessLog.getOrgId() == null || userBusinessLog.getOrgId() == -1L ? user.getDeptId() : userBusinessLog.getOrgId();

        List<SysDept> sysDeptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Long[] orgIds = new Long[sysDeptList.size()];
        for (int i = 0; i < sysDeptList.size(); i++) {
            SysDept sysDept = sysDeptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }


        Map<String,Object> params =userBusinessLog.getParams();

        params.put("orgIds", orgIds);
        params.put("orgId", null);

        // 业务员只能看到本人的日志
        SysDept org = getLoginUser().getUser().getDept();

        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        if (Objects.equals(org.getLevel(),TypeConstant.ORG_LEVEL_4) ) {
            if (roleMap.get("depart_leader").equals("0")) { // 业务员
                userBusinessLog.setEmpId(user.getUserId());
            }
        }
        String logDateStart=MapUtils.getString(params,"beginlogDate");
        String curdate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date());
        if(MapUtils.getString(params,"beginlogDate","").equals("")) {
            params.put("beginlogDate",curdate);
            params.put("endlogDate",curdate);
        }
        userBusinessLog.setParams(params);
        List<Map<String, Object>> ranks = new ArrayList<Map<String, Object>>();
        ranks =  userBusinessLogMapper.empAchieveSumRanking(userBusinessLog);

        List<Map<String,Object>> leaderUsers = iSysRoleService.getOrgLeaderUser();
        Map<String, String> leaderMap = new HashMap<String, String>();
        for (Map<String,Object> u : leaderUsers) {
            leaderMap.put(MapUtils.getString(u,"deptId",""),MapUtils.getString(u,"userName",""));
        }

        // 计算总计
        int todayVisitCount_total = 0;
        int todaySignedCount_total = 0;
        int todayIncomingCount_total = 0;
        int wechatFriendsTodayadd_total = 0;
        int todayIntroductionCount_total = 0;
        int todayIntroductionVisit_total = 0;
        int introductionSignedCount_total = 0;
        int todaySmsfollowCount_total = 0;
        int todayCallTime_total = 0;
        int todayTalkCount_total = 0;
        int todayDistributeCount_total = 0;
        int todayAddmustCount_total = 0;
        //double introductionSignedRate_total = 0;
        //double todaySignedRate_total = 0;
        for (Map<String, Object> rank : ranks) {
//            rank.put("full_org_name",sysDeptList selectOrgMap.get(MapUtils.getLong(rank,"org_id")));
            rank.put("org_leader", leaderMap.get(MapUtils.getString(rank,"org_id")));
            todayVisitCount_total += MapUtils.getDouble(rank,"todayVisitCount");
            todaySignedCount_total += MapUtils.getInteger(rank,"todaySignedCount");
            todayIncomingCount_total += MapUtils.getInteger(rank,"todayIncomingCount");
            wechatFriendsTodayadd_total += MapUtils.getInteger(rank,"wechatFriendsTodayadd");
            todayIntroductionCount_total += MapUtils.getInteger(rank,"todayIntroductionCount");
            todayIntroductionVisit_total += MapUtils.getInteger(rank,"todayIntroductionVisit");
            introductionSignedCount_total += MapUtils.getInteger(rank,"introductionSignedCount");
            todaySmsfollowCount_total += MapUtils.getInteger(rank,"todaySmsfollowCount");
            todayCallTime_total += MapUtils.getInteger(rank,"todayCallTime");
            todayTalkCount_total += MapUtils.getInteger(rank,"todayTalkCount");
            todayDistributeCount_total += MapUtils.getInteger(rank,"todayDistributeCount");
            todayAddmustCount_total += MapUtils.getInteger(rank,"todayAddmustCount");
            //introductionSignedRate_total += MapUtils.getInteger(rank,"introductionSignedRate");
            //todaySignedRate_total += MapUtils.getInteger(rank,"todaySignedRate");
        }

        resMap.put("selectOrgId", selectOrgId);
        resMap.put("userBusinessLog", userBusinessLog);
        resMap.put("list", ranks);
        resMap.put("roleMap", roleMap);
        resMap.put("todayDistributeTotal", todayDistributeCount_total);
        resMap.put("todayAddmustTotal", todayAddmustCount_total);

        return resMap;
    }
    /**
     * 部门排行
     * 20200725: 新增  --
     * @return
     */
    public Map<String, Object> getOrgBusinessLogs(int type, String query_type, UserBusinessLog userBusinessLog) {
        SysUser user = getLoginUser().getUser();
        Map<String,Object> resMap=new HashMap<String,Object>();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = userBusinessLog.getOrgId() == null || userBusinessLog.getOrgId() == -1L ? user.getDeptId() : userBusinessLog.getOrgId();

        List<SysDept> sysDeptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Long[] orgIds = new Long[sysDeptList.size()];
        for (int i = 0; i < sysDeptList.size(); i++) {
            SysDept sysDept = sysDeptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }


        Map<String,Object> params =userBusinessLog.getParams();

        params.put("orgIds", orgIds);
        params.put("orgId", null);

        // 业务员只能看到本人的日志
        SysDept org = getLoginUser().getUser().getDept();

        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        if (Objects.equals(org.getLevel(),TypeConstant.ORG_LEVEL_4) ) {
            if (roleMap.get("depart_leader").equals("0")) { // 业务员
                userBusinessLog.setEmpId(user.getUserId());
            }
        }
        String logDateStart=MapUtils.getString(params,"beginlogDate");
        String curdate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date());
        if(MapUtils.getString(params,"beginlogDate","").equals("")) {
            params.put("beginlogDate",curdate);
            params.put("endlogDate",curdate);
        }
        userBusinessLog.setParams(params);

        List<Map<String, Object>> ranks = new ArrayList<Map<String, Object>>();
        if ("3".equals(query_type)) { // 3.二级部门排行
            params.put("dept", "Y");
            ranks = userBusinessLogMapper.minOrgAchieveRanking(params);
        } else if ("2".equals(query_type)) { // 2.一级部门排行
            params.put("area", "Y");
            ranks = userBusinessLogMapper.middleOrgAchieveRanking(params);
        } else if ("1".equals(query_type)) { // 1.分公司排行
            ranks = userBusinessLogMapper.maxOrgAchieveRanking(params);
        }
        List<Map<String,Object>> leaderUsers = iSysRoleService.getOrgLeaderUser();
        Map<String, String> leaderMap = new HashMap<String, String>();
        for (Map<String,Object> u : leaderUsers) {
            leaderMap.put(MapUtils.getString(u,"deptId",""),MapUtils.getString(u,"userName",""));
        }

        // 计算总计
        int emp_cnt_total = 0;
        int todayVisitCount_total = 0;
        int todaySignedCount_total = 0;
        int todayIntroductionCount_total = 0;
        int todayIntroductionVisit_total = 0;
        int introductionSignedCount_total = 0;
        double todayVisitCountRate_total = 0;
        double todaySignedCountRate_total = 0;
        double todayIntroductionCountRate_total = 0;
        double todayIntroductionVisitRate_total = 0;
        double introductionSignedCountRate_total = 0;
        for (Map<String, Object> rank : ranks) {
//            rank.put("full_org_name", selectOrgMap.get(MapUtils.getLong(rank,"org_id")));
            rank.put("org_leader", leaderMap.get(MapUtils.getString(rank,"org_id")));
            emp_cnt_total += MapUtils.getDouble(rank,"emp_cnt");
            todayVisitCount_total += MapUtils.getDouble(rank,"todayVisitCount");
            todaySignedCount_total += MapUtils.getInteger(rank,"todaySignedCount");
            todayIntroductionCount_total += MapUtils.getInteger(rank,"todayIntroductionCount");
            todayIntroductionVisit_total += MapUtils.getInteger(rank,"todayIntroductionVisit");
            introductionSignedCount_total += MapUtils.getInteger(rank,"introductionSignedCount");
        }

        if (emp_cnt_total > 0) {
            todayVisitCountRate_total = new BigDecimal((double)todayVisitCount_total/(double)emp_cnt_total).setScale(2, RoundingMode.HALF_UP).doubleValue();
            todaySignedCountRate_total = new BigDecimal((double)todaySignedCount_total/(double)emp_cnt_total).setScale(2, RoundingMode.HALF_UP).doubleValue();
            todayIntroductionCountRate_total = new BigDecimal((double)todayIntroductionCount_total/(double)emp_cnt_total).setScale(2, RoundingMode.HALF_UP).doubleValue();
            todayIntroductionVisitRate_total = new BigDecimal((double)todayIntroductionVisit_total/(double)emp_cnt_total).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
        if (todayIntroductionVisit_total > 0) {
            introductionSignedCountRate_total = new BigDecimal((double)introductionSignedCount_total/(double)todayIntroductionVisit_total*100).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }

        if(emp_cnt_total>0){
            Map<String, Object> totalMap = new HashMap<String, Object>();
            totalMap.put("emp_cnt", emp_cnt_total);
            totalMap.put("todayVisitCount", todayVisitCount_total);
            totalMap.put("todaySignedCount", todaySignedCount_total);
            totalMap.put("todayIntroductionCount", todayIntroductionCount_total);
            totalMap.put("todayIntroductionVisit", todayIntroductionVisit_total);
            totalMap.put("introductionSignedCount", introductionSignedCount_total);
            totalMap.put("todayVisitCountRate", new BigDecimal(todayVisitCountRate_total).setScale(2, BigDecimal.ROUND_HALF_UP));
            totalMap.put("todaySignedCountRate", new BigDecimal(todaySignedCountRate_total).setScale(2, BigDecimal.ROUND_HALF_UP));
            totalMap.put("todayIntroductionCountRate", new BigDecimal(todayIntroductionCountRate_total).setScale(2, BigDecimal.ROUND_HALF_UP));
            totalMap.put("todayIntroductionVisitRate", new BigDecimal(todayIntroductionVisitRate_total).setScale(2, BigDecimal.ROUND_HALF_UP));
            totalMap.put("introductionSignedCountRate", new BigDecimal(introductionSignedCountRate_total).setScale(2, BigDecimal.ROUND_HALF_UP));
            ranks.add(totalMap);
        }

        resMap.put("list", ranks);
        resMap.put("roleMap", roleMap);

        return resMap;
    }

    /**
     * 过滤不包含某个角色集的用户
     * @param users
     * @param noLogRoles
     * @return
     */
    public List<SysUser> filterAllNeedLogUsers(List<SysUser> users, String noLogRoles) {
        List<SysUser> needLogUsers = new ArrayList<SysUser>();
        String[] noLogRolesArr=noLogRoles.split(",");
        for (SysUser sysUser : users) {
            boolean find = false;
            List<Map<String,Object>> userRole = iSysRoleService.getRoleInfoByUserId(sysUser.getUserId());
            for (Map<String,Object> role : userRole){
                for (String item : noLogRolesArr) {
                    if (item.equals(MapUtils.getString(role,"roleKey","") )){
                        find = true;
                        break;
                    }
                }
            }

            if (!find) {
                needLogUsers.add(sysUser);
            }
        }
        return needLogUsers;
    }
}
